package com.SFA.Message;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.FrameWork.Common.AbstractBaseActivity;
import com.FrameWork.Common.DRTL_ListViewUtil;
import com.FrameWork.Common.DRTL_ListViewUtil.IXListViewListener;
import com.FrameWork.Entity.MessageEntity;
import com.FrameWork.Utils.DateTimeUtils;
import com.FrameWork.Utils.Utils;
import com.SFA.R;
import com.umeng.analytics.MobclickAgent;
//import com.FrameWork.Common.myListView;
//import com.FrameWork.Common.PullToRefreshListView;
//import com.FrameWork.Common.PullToRefreshListView.OnRefreshListener;

public class MessageListActivity extends AbstractBaseActivity implements
		IXListViewListener {

	private MessageAdapter adapter;    
	private DRTL_ListViewUtil listView;
	private Handler mHandler;
	private int pageIndex = 1; // 页数
	private int total; // 总个数
	private GetDataTask dataTask; // 任务
	private LinearLayout layoutProgress = null;
//	private TextView titleView;
//	private Button btnReturn;
	private Intent intent;
	private String URL = null;
	private List<MessageEntity> list;
	public String LastRefreshTime; // 最后刷新时间manager
	private MessageLogicManager manager = new MessageLogicManager();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.drtl_listview);
//		titleView = (TextView) findViewById(R.id.title);
		intent = getIntent();
		layoutProgress = (LinearLayout) findViewById(R.id.layoutProgress);
		layoutProgress.setVisibility(View.VISIBLE);
		listView = (DRTL_ListViewUtil) findViewById(R.id.xListView);
		listView.setVisibility(View.GONE);
		listView.setXListViewListener(this);
		mHandler = new Handler();
		URL = intent.getStringExtra("URL");
		/************************************************************/
		// 打开页面时加载数据
		dataTask = new GetDataTask();
		dataTask.execute(pageIndex, 0);
		java.util.Date nowdate = new Date();
		listView.LastRefreshTime = listView.df.format(nowdate);
		

	}

	private OnTouchListener touch = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() != MotionEvent.ACTION_MOVE) {
				v.setBackgroundResource(0);
			}
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				v.setBackgroundResource(R.drawable.toolbar_click2);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				v.setBackgroundResource(0);
			}
			return false;
		}
	};

	private void onLoad() {
		listView.stopRefresh();
		listView.stopLoadMore();
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				dataTask = new GetDataTask();
				pageIndex = 1;
				dataTask.execute(pageIndex, 0); // 1表示第一页，0表示上部刷新
				onLoad();
				java.util.Date nowdate = new Date();
				listView.LastRefreshTime = listView.df.format(nowdate);
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				dataTask = new GetDataTask();
				dataTask.execute(pageIndex, 1);
				onLoad();
			}
		}, 2000);
	}

	/***
	 * 异步任务
	 */
	private class GetDataTask extends
			AsyncTask<Integer, Integer, List<MessageEntity>> {
		// 获取的RSSFeed集合

		public GetDataTask() {
			super();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected List<MessageEntity> doInBackground(Integer... params) {
			try {
				// 解析网络失败（解析缓存）
				// 上部拖拽
				if (params[1] == 0) {
					list = manager.getMessageByString(URL, context);
					if (manager.Successful) {
						total = 0;
					} else {
						publishProgress(1);
					}
				}

				return list;
			} catch (Exception err) {
				MobclickAgent.reportError(context, err.getMessage());
			}
			return null;
		}

		@SuppressWarnings("unused")
		@Override
		protected void onPostExecute(List<MessageEntity> listresult) {
			publishProgress(2);
			if (listresult == null) {
				listView.setVisibility(View.VISIBLE);
				layoutProgress.setVisibility(View.GONE);
				publishProgress(2);
				return;
			}
			if (listresult.size() <= 10) {
				listView.setPullLoadEnable(false);
			} else {
				listView.setPullLoadEnable(true);
			}
			// 获取当前要显示的数据
			total = listresult.size();// 记录总个数
			List<MessageEntity> listItem = new ArrayList<MessageEntity>();
			if (total >= pageIndex * 10) {
				listItem = listresult.subList(0, pageIndex * 10);
				pageIndex++;
			} else {
				if (total > pageIndex * 10 - 10) {
					listItem = listresult.subList(0, total);
					listView.setPullLoadEnable(false);
					pageIndex++;
				} else {
					return;
				}
			}
			adapter = new MessageAdapter(listItem, context);
			listView.setAdapter(adapter);
			listView.setSelection(listView.position);
			// loadRefrechDate();
			super.onPostExecute(listItem);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			if (values[0] == 2) {
				layoutProgress.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				/*
				 * Toast.makeText(context,
				 * getResources().getString(R.string.newslist_connectError),
				 * 1000) .show();
				 */
				return;
			}

			super.onProgressUpdate(values);
		}
	}

	/**
	 * Adapter的实现
	 * 
	 */
	public class MessageAdapter extends BaseAdapter {
		private List<MessageEntity> list;
		private LayoutInflater inflater;

		public MessageAdapter(List<MessageEntity> list, Context context) {
			super();
			this.list = list;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			final ViewHolder holder;
			if (convertView != null
			/* && convertView.getId() == R.id.newitem_layout */) {
				holder = (ViewHolder) convertView.getTag();
			} else {
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.drtl_listitem, null);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				holder.image = (ImageView) convertView.findViewById(R.id.image);

				convertView.setTag(holder);
			}
			MessageEntity entity = list.get(position);
			String title = entity.Title;
			holder.title.setText(title);
			holder.URL = entity.URL;
			holder.time.setText(DateTimeUtils.getSelects12Date(entity.Time));

			// 缓存加载图片
			holder.ImageUrl = entity.ImageURL;
//			convertView.setOnLongClickListener(new OnLongClickListener() {
//				
//				public boolean onLongClick(View v) {
//					// TODO Auto-generated method stub
//					Toast.makeText(MessageListActivity.this,"testesteststestest", Toast.LENGTH_LONG).show();
//					return true;
//				}
//			});
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(context, MessageViewActivity.class);
					intent.putExtra("URL", holder.URL);
					intent.putExtra("ShowToolBar", true);
					startActivity(intent);
					overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
				}
			});

			convertView.setOnTouchListener(touch);
			// 如果为null就不进行下载.
			if (holder.ImageUrl == null || holder.ImageUrl.equals("")) {
				holder.image.setImageResource(R.drawable.logo);
			} else {
				holder.show();
			}

			return convertView;
		}
	}

	/***
	 * 辅助holder
	 */
	public class ViewHolder {
		TextView title;
		TextView time;
		ImageView image;
		private String URL;
		private Bitmap bitmap = null;
		public String ImageUrl = ""; // 图片地址

		// 定义Handler对象
		private Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (bitmap != null) {

					image.setImageBitmap(bitmap);
				} else {
					image.setImageResource(R.drawable.logo);
				}

			}
		};

		/***
		 * 获取缓存图片.
		 */
		public void show() {
			new Thread(new Runnable() {
				@Override
				public void run() {
					if (!image.isDrawingCacheEnabled()) {
						// 或许图片地址
						try {
							bitmap = Utils.GetBitmap(ImageUrl, 100);
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						}
					} else {
						bitmap = image.getDrawingCache();
					}
					handler.sendEmptyMessage(0);

				}
			}).start();
		}
	}

}
